package com.mdxx.base.realm;

import com.alibaba.fastjson.JSON;
import com.mdxx.common.Catalog;
import com.mdxx.patrol.system.bean.SysMember;
import com.mdxx.patrol.system.bean.SysPermission;
import com.mdxx.patrol.system.bean.SysRole;
import com.mdxx.patrol.system.mapper.SysMemberMapper;
import com.mdxx.patrol.system.mapper.SysPermissionMapper;
import com.mdxx.patrol.system.mapper.SysRoleMapper;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by MD-1 on 2017/8/21.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysMemberMapper memberMapper;
    @Resource
    private SysPermissionMapper permissionMapper;

    private Logger logger = LoggerFactory.getLogger("认证授权");
    @Resource
    private PasswordHelper helper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("授权");
        System.out.println("授权doGetAuthorizationInfo");
        String username = (String) getAvailablePrincipal(principals);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<SysRole> sysRoles = roleMapper.queryByMemberUsername(username);
        Set<String> roleSet = new HashSet<>();
        for(SysRole role : sysRoles){
            roleSet.add(role.getTag());
        }
        info.setRoles(roleSet);

        List<SysPermission> permissions = permissionMapper.queryByMemberUsername(username);
        Set<String> permissionSet = new HashSet<>();
        for(SysPermission p : permissions){
            permissionSet.add(p.getTag());
        }
        permissionSet.add("member:edit");
        info.setStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("认证");
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        SysMember member = memberMapper.queryByUsername(username);
        if (member == null) {
            // 抛出 帐号找不到异常
            throw new UnknownAccountException();
        }

        //判断帐号是否锁定
        if (Boolean.FALSE.equals(member.getUsable())) {
            // 抛出 帐号锁定异常
            throw new LockedAccountException();
        }
       
//        member.setLastLoginTime(new Date());
//        memberMapper.updateById(member);
        //保存用户信息到session
        setSession("member",member);

        //保存用户的目录树到session
        userPermission(username);
//        String inputPassword = helper.calculatePassword("123456",member.getSalt());
//      System.out.println( "AAAA  "+inputPassword);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(member.getUsername(),
                member.getPassword(),
                ByteSource.Util.bytes(member.getSalt()),
                member.getUsername());
        return info;
    }

    /**
     * 添加数据到用户session中
     */
    private void setSession(String key, Object value){

        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser!=null){
            Session session = currentUser.getSession();
            session.setAttribute(key,value);
        }
    }

    /**
     * 保存权限树到session中
     */
    private void userPermission(String username){

        List<SysPermission> permissions = permissionMapper.queryByMemberUsername(username);

        List<Catalog> catalogs = new ArrayList<>();
        for(SysPermission p : permissions){
            if(p.getType()==1){
                Catalog catalog = new Catalog();
                catalog.setCatalogId(p.getId());
                catalog.setName(p.getName());
                catalog.setTag(p.getTag());
                catalog.setUrl(p.getUrl());
                catalog.setImg(p.getImgUrl());
                if(StringUtils.isEmpty(p.getUrl())){
                    catalog.setIsUrl(0);
                }else {
                    catalog.setIsUrl(1);
                }
                catalogs.add(catalog);
            }
        }
        for(SysPermission p : permissions){
            if(p.getType()==2){
                for(Catalog cc :catalogs){
                    if(p.getParentId()==cc.getCatalogId()){
                        Catalog c = new Catalog();
                        c.setCatalogId(p.getId());
                        c.setName(p.getName());
                        c.setTag(p.getTag());
                        c.setUrl(p.getUrl());
                        if(StringUtils.isEmpty(p.getUrl())){
                            c.setIsUrl(0);
                        }else {
                            c.setIsUrl(1);
                        }
                        cc.getCatalogs().add(c);
                    }
                }
            }
        }
        System.out.println(JSON.toJSONString(catalogs));

        setSession("catalogs",catalogs);
    }
}
